package com.superb.common.feign.interceptor;

import com.superb.common.utils.HeardersUtils;
import com.superb.common.utils.InnerIpUtils;
import com.superb.common.utils.IpUtils;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.util.Enumeration;

/**
 * @Author: ajie
 * @CreateTime: 2024-05-15 17:49
 */
@Configuration
public class FeignInterceptor implements RequestInterceptor {

    @Override
    public void apply(RequestTemplate template) {
        // 内部调用标记
        template.header(HeardersUtils.feign, "true");
        template.header(IpUtils.X_SUPERB_INNER_IP, InnerIpUtils.getLocalIp());
        template.header(IpUtils.X_SUPERB_IP, IpUtils.getCustomIp());
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            HttpServletRequest httpServletRequest = requestAttributes.getRequest();
            Enumeration<String> enumeration = httpServletRequest.getHeaderNames();
            enumeration.asIterator().forEachRemaining(headerName -> template.header(headerName, httpServletRequest.getHeader(headerName)));
        }
    }
}
